<template>
  <div>
    <div class="container" style="padding-top:5vh;" id="components-layout-demo-basic">
      <a-form class="form-sty" :form="form" @submit="handleSubmit">
        <a-row style="margin-bottom: 2vh;">
          <a-col :span="18" :offset="5">
            <p v-if="production.remark" style="color:red;">
              {{production.statusName}}
              原因:{{production.remark}}
            </p>
          </a-col>
        </a-row>
        <a-form-item style="margin-bottom:3vh;" label="ip地址" required v-bind="formItemLayout">
          <template v-for="(tag, index) in tags">
            <a-tooltip v-if="tag.length > 15" :key="tag + index" :title="tag">
              <a-tag
                :key="tag + index"
                :closable="true"
                :afterClose="() => handleClose(tag)"
              >{{`${tag.slice(0, 20)}...`}}</a-tag>
            </a-tooltip>
            <a-tag
              v-else
              :key="tag + index"
              :closable="true"
              :afterClose="() => handleClose(tag)"
            >{{tag}}</a-tag>
          </template>
          <a-input
            v-if="inputVisible"
            ref="input"
            type="text"
            size="small"
            :style="{ width: '140px',height: '32px' }"
            :value="inputValue"
            @change="handleInputChange"
            @blur="handleInputConfirm"
            @keyup.enter="handleInputConfirm"
          />
          <a-tag v-else @click="showInput" class="addTag">
            <a-icon type="plus" />新增
          </a-tag>
        </a-form-item>

        <a-form-item style="margin-bottom:3vh;" label="备注" v-bind="formItemLayoutTextarea">
          <a-textarea placeholder="备注" v-model="production.message" :rows="2" />
        </a-form-item>

        <a-form-item
          style="margin-bottom:3vh;"
          label="测试验收报告"
          required
          v-bind="formItemLayout"
          :help="`支持图片格式JPG、PNG，且每个文件大小不超过1M`"
        >
          <a-row>
            <a-col :span="10">
              <a-upload
                name="upfile"
                :headers="henderstoken"
                :fileList="fileList"
                action="/file/file/upload"
                :data="{to}"
                @change="handleChange"
              >
                <a-button>
                  <a-icon type="upload" />点击上传
                </a-button>
              </a-upload>
            </a-col>
            <a-col :span="10">
              <a
                href="static/授权委托书.docx"
                download="授权委托书.docx"
                target="_blank"
              >&nbsp;&nbsp;&nbsp;&nbsp;模板下载</a>
            </a-col>
          </a-row>
        </a-form-item>
        <a-form-item v-bind="formItemLayoutWithOutLabel">
          <a-button
            style="width:110px;margin-top:1vh;"
            html-type="submit"
            type="primary"
            :loading="loading"
          >提交</a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script>
import AForm from "ant-design-vue/es/form/Form";
import ATabs from "ant-design-vue/es/tabs";
import GlobalFooter from "../../layouts/GlobalFooter";
import AFormItem from "ant-design-vue/es/form/FormItem";
import AInput from "ant-design-vue/es/input/Input";
import AIcon from "ant-design-vue/es/icon";
import AInputGroup from "ant-design-vue/es/input/Group";
import AButton from "ant-design-vue/es/button/button";
import ACol from "ant-design-vue/es/grid/Col";
import ARow from "ant-design-vue/es/grid/Row";
import ACheckbox from "ant-design-vue/es/checkbox/Checkbox";
import AAlert from "ant-design-vue/es/alert/index";
import pick from "lodash.pick";
import api from "@/common/api";
import { get, post } from "@/common/api";
import moment from "moment";
const ATabPane = ATabs.TabPane;

let id = 0;
export default {
  name: "Login",
  components: {
    AAlert,
    ACheckbox,
    ACol,
    ARow,
    AButton,
    AInputGroup,
    AIcon,
    AInput,
    AFormItem,
    GlobalFooter,
    ATabPane,
    ATabs,
    AForm
  },
  data() {
    return {
      loading: false,
      // form: this.$form.createForm(this),
      henderstoken: {
        Authorization: localStorage.getItem("token"),
      },
      to:sessionStorage.getItem("memberNo") + "_" + sessionStorage.getItem("username"),
      size: 0,
      production: {
        merchantNo: "",
        merchantName: "",
        presentation: "",
        message: "",
        whiteListDTOList: {},
        remark: "",
        statusName: ""
      },
      tags: new Set(),
      inputVisible: false,
      inputValue: "",
      ips: [],
      fileList: [],
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 18, offset: 1 }
        }
      },
      formItemLayoutTextarea: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 12, offset: 1 }
        }
      },
      formItemLayoutWithOutLabel: {
        wrapperCol: {
          xs: { span: 24, offset: 0 },
          sm: { span: 18, offset: 5 }
        }
      }
    };
  },
  computed: {},
  beforeCreate() {
    this.form = this.$form.createForm(this);
  },
  created() {},
  mounted() {
    let self = this;
    if (this.$route.query.modify) {
      this.Modify();
    } else {
      this.production = this.$route.query.production;
      this.tags = [];
      console.log(this.production);
    }
  },
  methods: {
    Modify() {
      let modifyData = this.$route.query.modify;
      let ipList = modifyData.whiteListDTOList;
      let len = ipList.length;
      if (len > 0) {
        for (let i = 1; i < len + 1; i++) {
          let item = i;
          this.ips.push(ipList[i - 1].ip);
        }
      }
      console.log(this.ips);
      this.tags = this.ips;
      this.fileList.push({
        uid: "1",
        name: "测试报告.png",
        status: "done",
        url: "/file/file/download/" + modifyData.presentation
      });
      this.production = modifyData;
    },
    handleChange(info) {
      console.log(info);
      console.log(info.fileList);
      if (info.fileList.length == 0) {
        this.fileList = [];
        this.production.presentation = "";
        return false;
      } else {
        let pos = info.file.name.lastIndexOf(".");
        let lastName = info.file.name.substring(pos, info.file.name.length);
        let supportTypes = [".jpeg", ".png", ".jpg"]; // jpeg、 png
        if (supportTypes.indexOf(lastName.toLowerCase()) <= -1) {
          this.$message.error("上传报告仅支持jpg、png 2种格式！");
          return false;
        }

        if (info.file.size) {
          const isLt2M = info.file.size / 1024 / 1024 < 1;
          if (!isLt2M) {
            this.$message.error(`文件大小必须小于1MB!`);
            return false;
          }
        } else {
        }
      }
      let fileList = [...info.fileList];

      // 1. Limit the number of uploaded files
      //    Only to show two recent uploaded files, and old ones will be replaced by the new
      fileList = fileList.slice(-1);

      // 2. read from response and show file link
      fileList = fileList.map(file => {
        if (file.response) {
          // Component will show file.url as link
          file.url = file.response.url;
        }
        return file;
      });

      if (info.file.status === "done") {
        this.$message.success(`${info.file.name} 上传成功！`);
        this.production.presentation = info.fileList[0].response.data;
      }
      this.fileList = fileList;
    },

    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          if (this.tags.length == 0) {
            this.$message.warning("请填写ip地址！");
            return false;
          }
          if (this.production.presentation == "") {
            this.$message.warning("请上传测试验收报告！");
            return false;
          }
          console.log("production ", this.production);
          this.loading = true;
          let data = {
            id: this.production.id || null,
            merchantNo: this.production.merchantNo,
            merchantName: this.production.merchantName,
            presentation: this.production.presentation,
            message: this.production.message || null,
            ips: this.tags,
            memberNo: sessionStorage.getItem("memberNo")
          };
          api.proRequest(
            data,
            res => {
              console.log("res", res);
              if (res.code == "OK") {
                // this.email();
                this.$router.push("/org/Production/succ");
              } else {
                this.loading = false;
                console.log(res.message);
              }
            },
            err => {
              console.log("err", err);
            }
          );
        }
      });
    },

    email() {
      this.$axios.get("/agent/production/email").then(res => {
        console.log("res", res);
        if (res.data.code == "OK") {
          this.loading = false;
          let type = "success";
          this.$notification[type]({
            message: "邮件已发送",
            description: "请登录邮箱查看。"
          });
          this.$router.push("/userindex");
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    handleClose(removedTag) {
      const tags = this.tags.filter(tag => tag !== removedTag);
      console.log(tags);
      this.tags = tags;
    },

    showInput() {
      if (this.tags.length == 10) {
        this.$message.info("最多只能填写10个！");
        return false;
      }
      this.inputVisible = true;
      this.$nextTick(function() {
        this.$refs.input.focus();
      });
    },

    handleInputChange(e) {
      this.inputValue = e.target.value;
    },

    handleInputConfirm() {
      const inputValue = this.inputValue;

      let tags = this.tags;

      var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;

      if (this.inputValue != "" && !reg.test(this.inputValue)) {
        console.log(inputValue);
        this.$message.info("请填写合法的ip地址！");
        return false;
      } else {
        if (inputValue && tags.indexOf(inputValue) === -1) {
          tags = [...tags, inputValue];
        }
        console.log(tags);
        Object.assign(this, {
          tags,
          inputVisible: false,
          inputValue: ""
        });
      }
      if (inputValue == null || inputValue == "") {
        return false;
      }
      this.size++;
      if (this.size != tags.length) {
        console.log(tags.length);
        this.$message.info("ip地址不能重复！");
        this.size = tags.length;
        return false;
      } else {
        console.log(tags.length);
        console.log(this.size);
      }
    }
  }
};
</script>

<style lang="less" scoped>
#components-layout-demo-basic .ant-layout-content {
  height: 90vh;
}

#components-layout-demo-basic .ant-layout-footer {
  line-height: 1.5;
}

#components-layout-demo-basic .ant-layout-content {
  background: transparent;

  color: #fff;
  min-height: 120px;
  // line-height: 120px;
}

#components-layout-demo-basic > .ant-layout {
  margin-bottom: 48px;
}

#components-layout-demo-basic > .ant-layout:last-child {
  margin: 0;
}

/* .container {
    // width: 40%;
    margin: 20px auto;
    padding: 20px;
    // border:1px solid #333;
  } */

.form-sty {
  /* border: 1px solid #888; */
  padding: 30px 20px;
  width: 60%;
  margin: 0 auto;
  /* border-radius: 5px; */
  /* box-shadow: 3px 3px 15px #888888; */
}

span {
  cursor: pointer;
}

.type {
  padding: 10px;
  background: #eee;
  margin: 10px auto;
}

.span-wid {
  width: 300px;
  display: inline-block;
}

.ant-tag {
  line-height: 30px !important;
  height: 32px !important;
  margin-bottom: 10px;
  margin-right: 10px;
}

.a-sty {
  position: absolute;
  right: 18vw;
  top: 0px;
}

.addTag {
  background: #fff;
  border-style: dashed;
  width: 110px;
  text-align: center;
}

.ant-form-explain {
  margin-top: 15px !important;
}
</style>